package entityUpdater

import (
	"gitee.com/fierce_wolf/go-fox-edge-common/commEntity"
	"gitee.com/fierce_wolf/go-fox-edge-common/commRedisService"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Map"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Method"
	"gitee.com/fierce_wolf/go-fox-edge-common/edgeEntity"
)

type DeviceObjectMapper struct {
	updateTime      int64
	mapperEntityMap map[string]interface{}
}

type pair struct {
	Key   interface{}
	Value interface{}
}

func (e *DeviceObjectMapper) getObjectValue(manufacturer string, deviceType string, objectName string) (*pair, error) {
	val, err := Map.GetValue(e.mapperEntityMap, manufacturer, deviceType, objectName)
	if err != nil {
		return nil, err
	}
	if val == nil {
		return nil, err
	}

	return val.(*pair), nil
}

func (e *DeviceObjectMapper) getDeviceValue(manufacturer string, deviceType string) (map[string]interface{}, error) {
	val, err := Map.GetValue(e.mapperEntityMap, manufacturer, deviceType)
	if err != nil {
		return nil, err
	}
	if val == nil {
		return nil, err
	}

	return val.(map[string]interface{}), nil
}

func (e *DeviceObjectMapper) syncEntity() {
	updateTime := commRedisService.GetUpdateTime(edgeEntity.Type.DeviceMapperEntity.Type())
	if e.updateTime == updateTime {
		return
	}

	mapperEntityMap := make(map[string]interface{})
	finder := func(entity commEntity.IEntity) bool {
		value := entity.(*edgeEntity.DeviceMapperEntity)
		if Method.HasEmpty(value.Manufacturer, value.DeviceType, value.ObjectName, value.MapperName) {
			return false
		}

		pair := &pair{value.MapperName, value.MapperMode}
		Map.SetValue(mapperEntityMap, value.Manufacturer, value.DeviceType, value.ObjectName, pair)

		return true
	}

	commRedisService.FindEntityList(edgeEntity.Type.DeviceMapperEntity.Type(), finder)

	e.mapperEntityMap = mapperEntityMap
}
